import puppeteer from "puppeteer";
import { swaggerConfig } from '../../swaggerConfig'
import utilTool from "../../util/tool"
import { SwResult } from "../../store/swResult"
import { createEnumJosnFile } from "../service/createEnum"
import { createApiFile } from "../service/createApi"
import { createListFile } from "../service/createList"
import { createEditFile } from "../service/createEdit"
import { createRouterFile } from "../service/createRouter"
import { IMethod, IJson } from "../../interface/type"

export class IndexAction {
  private page: puppeteer.Page;
  constructor(page: puppeteer.Page) {
    this.page = page;
  }

  public filterPath(paths: IJson): IJson {
    const obj: IJson = {}
    for (const key of Object.keys(paths)) {
      if (key.indexOf(swaggerConfig.baseUrl) > -1) {
        obj[key] = paths[key]
      }
    }
    return obj
  }

  public async handleSwaggerHook(response: any) {
    if (response.url().indexOf("/swagger-resources") > 0) {
      const json: any[] = await response.json();
      const obj = json.find(it => { return swaggerConfig.serverName === it.name })
      const result = await utilTool.requestGet(swaggerConfig.href + obj.url)
      console.log('结果：', result)
      if (result.code && result.code !== 200) {
        console.log(result.message)
        return
      }
      const sw = new SwResult()
      sw.setDefinitions(result.definitions)

      sw.setPaths(this.filterPath(result.paths))
      sw.setBasePath(result.basePath)
      if (!result?.definitions) {
        console.log('未获得数据')
        return
      }
      // 创建枚举
      await createEnumJosnFile(sw)
      const list: IMethod[] = []
      for (const key of Object.keys(result.paths)) {
        const item = result.paths[key].post ? result.paths[key].post : result.paths[key].get
        item.description = item.description ? item.description : item.summary
        list.push({
          name: utilTool.getFunNameFromPath(key),
          link: item.operationId,
          description: utilTool.trimStr(item.description)
        })
      }
      // 创建接口文件
      await createApiFile(list, result.basePath)

      // const promises = names.map(x => getZhihuColumn(x))
      for (const sPage of swaggerConfig.pages) {
        await createListFile(sPage, sw)
        await createEditFile(sPage, sw)
        await createRouterFile(sPage)
      }
    }
  }

  public async startPageListen(): Promise<void> {
    console.log("开始页面监听");
    // const response = await this.page.waitForResponse(`${swaggerConfig.href}/swagger-resources`)
    // this.handleSwaggerHook(response)
    this.page.on("response", async (response: any) => {
      await this.handleSwaggerHook(response)
    })
  }
}
